package cn.ysym.tcsy;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import butterknife.ButterKnife;
import cn.ysym.dao.DealerDao;
import cn.ysym.dao.OfflineShippingDao;
import cn.ysym.dao.OfflineSumDao;
import cn.ysym.dao.ProductDao;
import cn.ysym.dao.PromotionDao;
import cn.ysym.dao.SettingDao;
import cn.ysym.model.Dealer;
import cn.ysym.model.OfflineShipping;
import cn.ysym.model.OfflineSum;
import cn.ysym.model.Product;
import cn.ysym.model.Promotion;
import cn.ysym.model.Setting;
import cn.ysym.util.CommonUtil;

public class OfflineShippingActivity extends AppCompatActivity {

    private SettingDao settingDao;
    private DealerDao dealerDao;
    private ProductDao productDao;
    private PromotionDao promotionDao;
    private OfflineSumDao offlineSumDao;
    private OfflineShippingDao offlineShippingDao;

    private ProgressBar progressBar;
    private RadioGroup rgShippingType;
    private EditText etDealer;
    private ListView lvDealer;
    private EditText etProduct;
    private ListView lvProduct;
    private EditText etPromotion;
    private ListView lvPromotion;
    private EditText etCode;
    private CheckBox cbVirtualBig;
    private ListView lvResult;
    private EditText etShippingId;

    private OfflineSum curSum;
    private TextView tvSuccNum;
    private int succNum = 0;
    private ArrayAdapter<String> resultAdapter;

    private UpDataTask upDataTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_shipping);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("离线出库");

        settingDao = new SettingDao(this);
        dealerDao = new DealerDao(this);
        productDao = new ProductDao(this);
        promotionDao = new PromotionDao(this);
        offlineSumDao = new OfflineSumDao(this);
        offlineShippingDao = new OfflineShippingDao(this);

        progressBar = (ProgressBar) findViewById(R.id.progressBarOnline);

        etDealer = (EditText) findViewById(R.id.etDealer);
        lvDealer = (ListView) findViewById(R.id.lvDealer);
        lvDealer.setVerticalScrollBarEnabled(true);

        etProduct = (EditText) findViewById(R.id.etProduct);
        lvProduct = (ListView) findViewById(R.id.lvProduct);
        lvProduct.setVerticalScrollBarEnabled(true);
        etShippingId = findViewById(R.id.etShippingId);

   /*     List<Product> ps = productDao.query("");
        String str = ps.get(1).getProductName();    //目前只有两个产品，默认自动选中第二个产品
        etProduct.setText(str);*/

        etDealer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ArrayAdapter<String> tAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
                    List<Dealer> models = dealerDao.query("");
                    for (Dealer model : models) {
                        tAdapter.add(CommonUtil.formatStr(model.getDealerId() + " " + model.getDealerName()));
                    }
                    lvDealer.setAdapter(tAdapter);
                    lvDealer.setVisibility(View.VISIBLE);
                } else {
                    lvDealer.setVisibility(View.GONE);
                }
            }
        });

        etDealer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                ArrayAdapter<String> tAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
                List<Dealer> models = dealerDao.query(s.toString());
                for (Dealer model : models) {
                    tAdapter.add(CommonUtil.formatStr(model.getDealerId() + " " + model.getDealerName()));
                }
                lvDealer.setAdapter(tAdapter);
                lvDealer.setVisibility(View.VISIBLE);
            }
        });

        lvDealer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                etDealer.setText(text);
                lvDealer.setVisibility(View.GONE);
                etCode.requestFocus();
            }
        });

        etProduct.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
                    List<Product> ps = productDao.query("");
                    for (Product p : ps) {
                        productAdapter.add(CommonUtil.formatStr(p.getProductName()));
                    }
                    lvProduct.setAdapter(productAdapter);
                    lvProduct.setVisibility(View.VISIBLE);
                } else {
                    lvProduct.setVisibility(View.GONE);
                }
            }
        });

        etProduct.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
                List<Product> ps = productDao.query(s.toString());
                for (Product p : ps) {
                    productAdapter.add(CommonUtil.formatStr(p.getProductName()));
                }
                lvProduct.setAdapter(productAdapter);
                lvProduct.setVisibility(View.VISIBLE);
            }
        });

        lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                etProduct.setText(text);
                lvProduct.setVisibility(View.GONE);
                etCode.requestFocus();
            }
        });

        etPromotion = (EditText) findViewById(R.id.etPromotion);
        lvPromotion = (ListView) findViewById(R.id.lvPromotion);
        lvPromotion.setVerticalScrollBarEnabled(true);

        etPromotion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ArrayAdapter<String> pAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
                    List<Promotion> ps = promotionDao.query("");
                    for (Promotion p : ps) {
                        pAdapter.add(CommonUtil.formatStr(p.getPromotionId() + " " + p.getPromotionName()));
                    }
                    lvPromotion.setAdapter(pAdapter);
                    lvPromotion.setVisibility(View.VISIBLE);
                } else {
                    lvPromotion.setVisibility(View.GONE);
                }
            }
        });

        etPromotion.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                ArrayAdapter<String> pAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
                List<Promotion> ps = promotionDao.query(s.toString());
                for (Promotion p : ps) {
                    pAdapter.add(CommonUtil.formatStr(p.getPromotionId() + " " + p.getPromotionName()));
                }
                lvPromotion.setAdapter(pAdapter);
                lvPromotion.setVisibility(View.VISIBLE);
            }
        });

        lvPromotion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                etPromotion.setText(text);
                lvPromotion.setVisibility(View.GONE);
                etCode.requestFocus();
            }
        });

        etCode = (EditText) findViewById(R.id.etCode);
        etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    if (upDataTask == null) {
                        progressBar.setVisibility(View.VISIBLE);

                        String shippingType = "1";
                        RadioButton rbChecked = (RadioButton) findViewById(rgShippingType.getCheckedRadioButtonId());
                        if ("退货".equals(rbChecked.getText())) shippingType = "2";
                        else if ("调货".equals(rbChecked.getText())) shippingType = "3";

                        String shippingId = etShippingId.getText().toString();
          /*              if(shippingType.equals("1") && shippingId.trim().length() < 1){
                            Toast.makeText(getApplicationContext(), "发货单号必须输入",Toast.LENGTH_SHORT).show();
                            etCode.setText("");
                            return false;
                        }*/

                        String dealerId = etDealer.getText().toString();
                        int tIndex = dealerId.indexOf(" ");
                        if (tIndex > 0) dealerId = dealerId.substring(0, tIndex);

                        String productId = etProduct.getText().toString();
                        productId = productId.replace("\n", "");
                        int tIndex1 = productId.indexOf(" ");
                        if (tIndex1 > 0) productId = productId.substring(0, tIndex1);

                        String promotionId = etPromotion.getText().toString();
                        int tIndex2 = promotionId.indexOf(" ");
                        if (tIndex2 > 0) promotionId = promotionId.substring(0, tIndex2);

                        String code = CommonUtil.cleanCode(etCode.getText().toString());
                        etCode.setText(code);

                        String virtualBig = "0";
                        if (cbVirtualBig.isChecked()) {
                            virtualBig = "1";
                        }

                        String procDesc = "出库";
                        Dealer dealer = dealerDao.queryById(dealerId);
                        if (dealer != null) procDesc += "：" + dealer.getDealerName();

                        upDataTask = new UpDataTask(shippingType, dealerId, productId, promotionId, code, virtualBig, procDesc, shippingId);
                        upDataTask.execute((Void) null);
                    }
                }
                return false;
            }
        });

        cbVirtualBig = (CheckBox) findViewById(R.id.ckVirtualBig);
        rgShippingType = (RadioGroup) findViewById(R.id.rgShippingType);
        tvSuccNum = (TextView) findViewById(R.id.tvSuccNum);
        //扫码记录
        lvResult = (ListView) findViewById(R.id.lvResult);
        resultAdapter = new ArrayAdapter<String>(OfflineShippingActivity.this, R.layout.list_view);
        lvResult.setAdapter(resultAdapter);
    }

    public class UpDataTask extends AsyncTask<Void, Void, Boolean> {
        private String shippingType;
        private String dealerId;
        private String productId;
        private String promotionId;
        private String code;
        private String virtualBig;
        private String procDesc;
        private String shippingId;

        public UpDataTask(String shippingType, String dealerId, String productId, String promotionId, String code, String virtualBig, String procDesc, String shippingId) {
            this.shippingType = shippingType;
            this.dealerId = dealerId;
            this.productId = productId;
            this.promotionId = promotionId;
            this.code = code;
            this.virtualBig = virtualBig;
            this.procDesc = procDesc;
            this.shippingId = shippingId;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (offlineShippingDao.isExist(code)) return false;
            else {
                if (curSum == null || !shippingType.equals(curSum.getProcType()) || !procDesc.equals(curSum.getProcDesc())) {
                    Setting userName = settingDao.query("userName");
                    curSum = new OfflineSum();
                    curSum.setAccount(userName.getSettingValue());
                    curSum.setUpFailNum(0);
                    curSum.setUpSuccNum(0);
                    curSum.setProcDesc(procDesc);
                    curSum.setProcNum(1);
                    curSum.setProcType(shippingType);
                    offlineSumDao.insert(curSum);

                    curSum = offlineSumDao.getLast();
                } else {
                    curSum.setProcNum(curSum.getProcNum() + 1);
                    offlineSumDao.update(curSum);
                }

                OfflineShipping os = new OfflineShipping();
                os.setDealerId(dealerId);
                os.setProductId(productId);
                os.setPromotionId(promotionId);
                os.setCode(code);
                os.setVirtualBig(virtualBig);
                os.setSumId(curSum.getId());
                os.setUpSucc("0");
                os.setScanTime(CommonUtil.getDateTimeStr("yyyyMMddHHmmss"));
                os.setShippingId(shippingId);
                offlineShippingDao.insert(os);

                return true;
            }
        }

        @Override
        protected void onPostExecute(final Boolean ret) {
            upDataTask = null;
            progressBar.setVisibility(View.GONE);

            if (ret) {
                succNum++;
                tvSuccNum.setText(String.valueOf(succNum));
                resultAdapter.add(code);
            } else {
                CommonUtil.playSound(OfflineShippingActivity.this);
                Toast.makeText(getApplicationContext(), "已扫码", Toast.LENGTH_SHORT).show();
            }

            etCode.setText("");
            etCode.requestFocus();
        }

    }
}
